<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends Controller
{
	private $_template_f;
	private $_lang;
	private $_numItem = 20;
	private $_format_zone_xml = 'http://admicro2.vcmedia.vn/adt/cpc/zones.xml';
	private $_folderImageStore = 'uploads/images/';
	private $_script_zone_format = '<div id="ssvzone_%s"></div><script type="text/javascript" src="http://admicro1.vcmedia.vn/cpc/ssvzone_%s.js" id="Script_zone_%s"></script>';
	
	function __construct()
	{
		parent::Controller();
		$this->_lang = $this->mycommon->getLangCode();
		$this->_template_f = $this->config->item('template_f');
		$this->load->language('common', $this->_lang);
		$common_lang = $this->lang->line('common_lang');
		if(!$this->session->userdata('uname') || $this->session->userdata('permitid') > -1)
		{
			redirect(site_url('/login'));
			die();
		}
		else
		{
			$permitid = $this->session->userdata('permitid');
			if(!is_numeric($permitid) || $permitid > 0)
			{
				show_error($common_lang['access_denied']);
				die();
			}
		}
		$this->load->model('user/user_model');
		$this->load->language('common', $this->_lang);
		$this->load->language('user/user', $this->_lang);
	}
	
	function _loadHeader($title = '')
	{
		$header = array();
		$header['title'] = $title == '' ? 'Self serving' : $title;
		$header['template_f'] = $this->_template_f;
		$header['username'] = '';
		$header['userid'] = '';
		$header['permitid'] = '';
		$header['lang'] = $this->_lang;
		$header['module_name'] = 'home';
		if($this->session->userdata('uname'))
		{
			$header['username'] = $this->session->userdata('uname');
			$header['userid'] = $this->session->userdata('uid');
			$header['permitid'] = $this->session->userdata('permitid');
		}
		$this->load->view($this->_template_f . 'preheader_view');
		$this->load->view($this->_template_f . 'header_view', $header);
	}
	
	function _loadMenu()
	{
		$data = array();
		$data['username'] = '';
		$data['userid'] = '';
		$data['permitid'] = '';
		$data['lang'] = $this->_lang;
		if($this->session->userdata('uname'))
		{
			$data['username'] = $this->session->userdata('uname');
			$data['userid'] = $this->session->userdata('uid');
			$data['permitid'] = $this->session->userdata('permitid');
		}
		$data['common_lang'] = $this->lang->line('common_lang');
		$this->load->view($this->_template_f . 'menu_view', $data);
	}
	
	function _loadFooter()
	{
		$this->load->view($this->_template_f . 'footer_view');
	}
	
	function index()
	{
		$this->view();
	}
	
	function create()
	{
		$data = array();
		
		$data['lang'] = $this->lang->line('user_lang');
		$data['errUser'] = '';
		$data['errPass'] = '';
		$data['errEmail'] = '';
		$data['errName'] = '';
		$data['errPhone'] = '';
		
		$username = strtolower(trim($this->input->post('username',true)));
		$password = $this->input->post('password',true);
		$repass = $this->input->post('repassword',true);
		$address = $this->input->post('address',true);
		$email = $this->input->post('email',true);
		$fullname = $this->input->post('fullname',true);
		$phone = $this->input->post('phone',true);
		$role = $this->input->post('roleid',true);
		if($role == '') $role = 3;
		$issale = 0;
		if((int)$role == -7)
		{
			$role = 3;
			$issale = 1;
		}
		$block = (int)$this->input->post('block',true);
		$active = (int)$this->input->post('active',true);
		
		if(isset($_POST['username']))
		{
			if($username == '')
			{
				$data['errUser'] = $data['lang']['enter_username'];
			}
			elseif(!$this->mycommon->validUsername($username))
			{
				$data['errUser'] = $data['lang']['username_invalid'];
			}
			elseif(!$this->user_model->check_username_available($username))
			{
				$data['errUser'] = $data['lang']['username_existst'];
			}
			
			if($password == '')
			{
				$data['errPass'] = $data['lang']['enter_password'];
			}
			elseif($repass == '')
			{
				$data['errPass'] = $data['lang']['enter_repassword'];
			}
			elseif($password != $repass)
			{
				$data['errPass'] = $data['lang']['password_not_match'];
			}
			
			if($email == '')
			{
				$data['errEmail'] = $data['lang']['enter_email'];
			}
			elseif(!$this->user_model->checkEmail($email))
			{
				$data['errEmail'] = $data['lang']['email_invalid'];
			}
			elseif(!$this->user_model->check_email_available($email))
			{
				$data['errEmail'] = $data['lang']['email_exists'];
			}
			
			if($fullname == '')
			{
				$data['errName'] = $data['lang']['enter_fullname'];
			}
			
			if($phone == '')
			{
				$data['errPhone'] = $data['lang']['enter_phone'];
			}
			elseif(!is_numeric($phone))
			{
				$data['errPhone'] = $data['lang']['phone_invalid'];
			}
			
			
			if($data['errUser']=='' && $data['errPass']=='' &&
				$data['errEmail']=='' && $data['errName']=='' && $data['errPhone']==''
			)
			{
				$this->user_model->add($username,md5($password),$fullname,$email,$address,$phone,$role,$block,$active);
				redirect(site_url('user'));
				die();
			}
		}
		
		$data['username'] = $username;
		$data['password'] = $password;
		$data['repass'] = $repass;
		$data['address'] = $address;
		$data['email'] = $email;
		$data['fullname'] = $fullname;
		$data['phone'] = $phone;
		$data['block'] = $block;
		$data['active'] = $active;
		$data['role'] = (int)$role;
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f . 'user/user_create', $data);
		$this->_loadFooter();
	}
	
	function edit()
	{
		$uid = (int)$this->uri->rsegment(3);
		$user = $this->user_model->get_user_info($uid);
		$user['repass'] = '';
		
		$data = array();
		$data['lang'] = $this->lang->line('user_lang');
		//$data['groups'] = $this->user_model->get_group_list();
		$data['sale'] = array();

		$data['errUser'] = '';
		$data['errPass'] = '';
		$data['errEmail'] = '';
		$data['errName'] = '';
		$data['errPhone'] = '';
		
		if(isset($_POST['updateUser']))
		{
			$user['password'] = $this->input->post('password',true);
			$user['repass'] = $this->input->post('repassword',true);
			$user['address'] = $this->input->post('address',true);
			$user['truename']= $this->input->post('fullname',true);
			$user['phone'] = $this->input->post('phone',true);
			$user['role'] = $this->input->post('roleid',true);
			if($user['role'] == '') $user['role'] = 3;
			$user['block'] = (int)$this->input->post('block',true);
			$user['active'] = (int)$this->input->post('active',true);
            
			if($user['password'] != '')
			{
				if($user['repass'] == '')
				{
					$data['errPass'] = $data['lang']['enter_repassword'];
				}
				elseif($user['password'] != $user['repass'])
				{
					$data['errPass'] = $data['lang']['password_not_match'];
				}
				else $user['password'] = md5($user['password']);
			}
			
			if($user['email'] != $this->input->post('email',true))
			{
				$user['email'] = $this->input->post('email',true);
				if($user['email'] == '')
				{
					$data['errEmail'] = $data['lang']['enter_email'];
				}
				elseif(!$this->user_model->checkEmail($user['email']))
				{
					$data['errEmail'] = $data['lang']['email_invalid'];
				}
				elseif(!$this->user_model->check_email_available($user['email']))
				{
					$data['errEmail'] = $data['lang']['email_exists'];
				}
			}
			
			if($user['truename'] == '')
			{
				$data['errName'] = $data['lang']['enter_fullname'];
			}
			
			if($user['phone'] == '')
			{
				$data['errPhone'] = $data['lang']['enter_phone'];
			}
			elseif(!is_numeric($user['phone']))
			{
				$data['errPhone'] = $data['lang']['phone_invalid'];
			}
			
			if($data['errUser']=='' && $data['errPass']=='' && $data['errEmail']=='' && $data['errName']=='' && $data['errPhone']=='')
			{
				$this->user_model->update($user['user_id'],$user['password'],$user['truename'],$user['email'],$user['phone'],
				$user['address'],$user['block'],$user['active'],$user['role']);
				redirect(site_url('user'));
			}
		}
		
		$data['username'] = $user['username'];
		$data['password'] = $user['password'];
		$data['repass'] = $user['repass'];
		$data['address'] = $user['address'];
		$data['email'] = $user['email'];
		$data['fullname'] = $user['truename'];
		$data['phone'] = $user['mobile'];
		$data['block'] = $user['block'];
		$data['active'] = $user['active'];
		$data['role'] = $user['role'];
		
		$this->_loadHeader();
		$this->_loadMenu();
		$this->load->view($this->_template_f . 'user/user_edit', $data);
		$this->_loadFooter();
	}
	
	function view()
	{
		$type = $this->input->get('type');
		$level = $this->input->get('level')=='' ? -2 : $this->input->get('level');
		$keyword = trim($this->input->get('keyword'));
		$cPage = $this->input->get('cpage');

		
		$type = ($type == '') ? 'active' : $type;
		$cPage = (is_numeric($cPage) && $cPage > 0) ? $cPage : 1;
		$start = ($cPage - 1) * $this->_numItem;
		$cmofsale = trim($this->input->get('cmofsale',true));
		
		$data = array();
		$dat['lang'] = $this->_lang;
		$data['user_lang'] = $this->lang->line('user_lang');
		// load header
		$this->_loadHeader($data['user_lang']['module_title']);
		
		// load menu
		$this->_loadMenu();
		
		// load content
		$data['lang'] = $this->lang->line('user_lang');
		$lstUserInfo = $this->user_model->get_all($type, $level, $start, $this->_numItem,$keyword);
		$data['lstUser'] = $lstUserInfo['lstUser'];
		$data['iCount'] = $lstUserInfo['iCount'];
		$data['pCount'] = $lstUserInfo['pCount'];
		$data['numCurrItem'] = count($data['lstUser']);
		$data['lstPaging'] = $this->mycommon->getListPaging($cPage, $data['pCount']);
        $data['keyword']=$keyword;
		$data['type'] = $type;
		$data['level'] = $level;
		$data['cPage'] = $cPage;
		$this->load->view($this->_template_f . 'user/user_view', $data);
	}
	
	function action()
	{
		$data = array();
		$data['code'] = 0;
		$userId = $this->input->get('id');
		$action = strtolower($this->input->get('action'));
		
		$userId = (is_numeric($userId) && $userId > 0) ? $userId : 0;
		if($userId > 0)
		{
			$uidSetAction = (int)$this->session->userdata('uid');
			
			$this->user_model->user_set_action($action, $userId, $uidSetAction);
			$data['code'] = 1;
		}
		echo json_encode($data);
	}
	
	function listgroup()
	{
		$data = array();
		$data['lang'] = $this->lang->line('user_lang');
		
		$data['group'] = array();
		$data['group']['id'] = (int)$this->input->get('gid', true);
		$data['group']['name'] = '';
		$data['group']['description'] = '';
		$data['group']['zones'] = array();
		$data['group']['allowfree'] = 1;
		if($data['group']['id'] > 0)
		{
			$item = $this->user_model->get_group_info($data['group']['id']);
			if($item != null && count($item) > 0)
			{
				$data['group']['name'] = $item['groupname'];
				$data['group']['description'] = $item['description'];
				$data['group']['zones'] = explode(',', $item['lstzone']);
				$data['group']['zones'] = array_filter($data['group']['zones']);
				$data['group']['allowfree'] = (int)$item['allowfree'];
			}
			else $data['group']['id'] = 0;
		}
		
		$data['items'] = $this->user_model->get_group_list();

		$data['lstZone'] = $this->user_model->get_list_zones();
		$data['lstDisable'] = $this->user_model->selfserving_admin_agency_num_active_user('-1');
		$this->_loadHeader($data['lang']['module_title']);
		$this->_loadMenu();
		
		$this->load->view($this->_template_f . 'user/user_listgroup', $data);
		
		$this->_loadFooter();
	}
	
	function editgroup()
	{
		$data = array();
		$data['lang'] = $this->lang->line('user_lang');
		
		$gid = (int)$this->input->get('gid', true);

		if($gid > 0)
		{
			$data['group'] = $this->user_model->get_group_info($gid);
		}
		else
		{
			redirect('user/listgroup');
			die();
		}
		
		//$data['items'] = $this->user_model->get_group_list();

		$data['lstZone'] = $this->user_model->get_list_zones();
		
		$this->_loadHeader($data['lang']['module_title']);
		$this->_loadMenu();
		
		$this->load->view($this->_template_f . 'user/user_editgroup', $data);
		
		$this->_loadFooter();
	}
	
	function addgroup()
	{
		$data = array();
		$data['lang'] = $this->lang->line('user_lang');
		
		$data['lstZone'] = $this->user_model->get_list_zones();
		
		$this->_loadHeader($data['lang']['module_title']);
		$this->_loadMenu();
		
		$this->load->view($this->_template_f . 'user/user_addgroup', $data);
		
		$this->_loadFooter();
	}
	
	function listzone()
	{
		$data = array();
		$data['lang'] = $this->lang->line('user_lang');
		
		$data['zones'] = $this->user_model->get_list_zone();
		/*print_r($data['zones']);
		return;*/
		
		$this->_loadHeader($data['lang']['zone_title']);
		$this->_loadMenu();
		
		$this->load->view($this->_template_f . 'user/user_listzone', $data);
		
		$this->_loadFooter();
	}
	
	function editzone()
	{
		$data = array();
		$data['lang'] = $this->lang->line('user_lang');
		
		$data['zone_id'] = (int)$this->input->get('id', true);
		$data['zone_name'] = '';
		$data['format_id'] = 0;
		$data['chanel_id'] = 0;
		$data['zone_des'] = '';
		if($data['zone_id'] > 0)
		{
			$row = $this->user_model->get_list_zone($data['zone_id']);
			$row = $row[0];
			if(count($row > 0))
			{
				$data['zone_name'] = $row['zonename'];
				$data['zone_des'] = $row['description'];
				$data['format_id'] = $row['formatid'];
				$data['chanel_id'] = $row['channelid'];
			}
		}
		else
		{
			redirect(site_url('user/listzone'));
			die();
		}

		$xml = file_get_contents($this->_format_zone_xml);
		$xml = new SimpleXMLElement($xml);
		$data['items'] = $xml->children();
		$data['chanel'] = $this->user_model->get_list_chanel();
				
		$this->_loadHeader($data['lang']['zone_title']);
		$this->_loadMenu();
		
		$this->load->view($this->_template_f . 'user/user_editzone', $data);
		
		$this->_loadFooter();
	}
	
	function addzone()
	{
		$data = array();
		$data['lang'] = $this->lang->line('user_lang');
		
		$xml = file_get_contents($this->_format_zone_xml);
		$xml = new SimpleXMLElement($xml);
		$data['items'] = $xml->children();
		$data['chanel'] = $this->user_model->get_list_chanel();
				
		$this->_loadHeader($data['lang']['zone_title']);
		$this->_loadMenu();
		
		$this->load->view($this->_template_f . 'user/user_addzone', $data);
		
		$this->_loadFooter();
	}
	
	function viewzone()
	{
		$data = array();
		$data['folderImageStore'] = $this->_folderImageStore;
		$data['lang'] = $this->lang->line('user_lang');
		$data['zone_id'] = (int)$this->input->get('id', true);
		if($data['zone_id'] > 0)
		{
			$row = $this->user_model->get_list_zone($data['zone_id']);
			//Neu khong co
			if($row == null || count((array)$row) == 0)
			{
				redirect(site_url('user/listzone')); die();
			}
			$row = $row[0];
			$xml = file_get_contents($this->_format_zone_xml);
			$xml = new SimpleXMLElement($xml);
			$format = $xml->children();
			
			$lstFormat = array();
			foreach($format as $item)
				if($item->id == $row['formatid'])
				{
					$lstFormat = &$item;
					break;
				}
			$data['format_id'] = $row['formatid'];
			$data['zone'] = $lstFormat;
		}
		else
		{
			redirect(site_url('user/listzone')); die();
		}
		
		$page = (int)$this->input->get('page', true);
		if($page <= 0) $page = 1;
		$limit = 20;
		list($data['items'], $data['totalPage']) = $this->user_model->list_zone_items($data['zone_id'], $page, $limit);
		if($page > $data['totalPage']) $page = $data['totalPage'];
		
		//Lay duong dan anh baner
		$this->load->library('mycommon');
		for($i = 0; $i < count($data['items']); $i++)
		{
			$data['items'][$i]['filename'] = $this->mycommon->getBannerImagPath('', '', $data['items'][$i]['filename'], strtotime($data['items'][$i]['createtime']));
		}
		
		$data['page'] = $page;
		$data['script_zone_format'] = $this->_script_zone_format;
		
		$this->_loadHeader($data['lang']['zone_title']);
		$this->_loadMenu();

		$this->load->view($this->_template_f . 'user/user_viewzone', $data);
		
		$this->_loadFooter();
	}
	
	function savegroup()
	{
		if(isset($_POST['groupname']))
		{
			$lang = $this->lang->line('user_lang');
			
			$groupid = (int)$this->input->post('groupid',true);
			
			$groupname = $this->input->post('groupname',true);
			$description = $this->input->post('description',true);
			$lstZone = $this->input->post('lstzone',true);
			$allowfree = (int)$this->input->post('allowfree',true);
			$discount = (int)$this->input->post('discount',true);
			$ispostpaid = (int)$this->input->post('ispostpaid',true);
			$typegroup = (int)$this->input->post('typegroup',true);
			
			if($groupname == '')
			{
				redirect(site_url('user/listgroup/?msg='.$lang['enter_groupname']));
				die();
			}
			
			/*if(!is_array($lstZone) || count($lstZone) == 0)
			{
				redirect(site_url('user/listgroup/?msg='.$lang['select_zone']));
				die();
			}*/
			
			//loc zone list
			if(!is_array($lstZone) || count($lstZone) == 0) $lstZone = '';
			else
			{
				$lstZone = implode(',', array_filter($lstZone));
				for($i = 0; $i < count($lstZone); $i++) $lstZone[$i] = (int)$lstZone[$i];
			}
			
			if($groupid > 0)
			{	//Update
				$this->user_model->update_group($groupid, $groupname, $description, $lstZone, $allowfree, $discount, $ispostpaid, $typegroup);
				redirect(site_url('user/listgroup/?msg='.$lang['update_zone_success']));
				die();
			}
			else	//Insert
			{
				$this->user_model->add_group($groupname, $description, $lstZone, $allowfree, $discount, $ispostpaid, $typegroup);
				redirect(site_url('user/listgroup/?msg='.$lang['create_zone_success']));
				die();
			}
		}
		
		redirect(site_url('user/listgroup'));
		return;
	}
	
	function savezone()
	{
		if(isset($_POST['zone_name']))
		{
			$zone_id = (int)$this->input->post('zone_id', true);
			$zone_name = $this->input->post('zone_name', true);
			$zone_des = $this->input->post('zone_des', true);
			$chanel_id = (int)$this->input->post('chanel', true);
			$format_id = $this->input->post('format', true);
			
			if($zone_name != '' && chanel_id > 0 && format_id > 0)
			{
				$this->user_model->save_zone($zone_id, $zone_name, $zone_des, $chanel_id, $format_id);
			}
		}
		redirect('user/listzone');
	}
	
	function preview_format()
	{
		$data = array();
		$format_id = (int)$this->input->get('id', true);
		
		$xml = file_get_contents($this->_format_zone_xml);
		$xml = new SimpleXMLElement($xml);
		$format = $xml->children();
		
		$data['fm'] = array();
		foreach($format as $item)
		if($item->id == $format_id)
		{
			$data['fm'] = &$item;
			break;
		}
		$this->load->view($this->_template_f . 'user/user_preview_format', $data);
	}
    function get_list_campaign()
    {
        $userid = $this->input->get('userid');
        $temp = $this->user_model->get_user_info($userid);
        $groupid=$temp[0]['groupid'];
        $data['info']=$this->user_model->selfserving_get_lstcampaign_to_set_by_userid($userid);
        $this->load->view($this->_template_f . 'user/user_assign_campaign', $data);
    }
    function assign()
    {
        $userid=$this->input->get('userid');
        $lstCampaign=$this->input->get('lst');
        $count = $this->user_model->selfserving_users_campaign_update($userid,$lstCampaign);
        if($count==true)
        {
            echo 'Cập nhật thành công';
        }else{
            echo 'Có lỗi xảy ra,xin hãy thử lại!';
        } 
    }
    
    function ajaxGetSaleInGroup()
    {
    	$groupid = (int)$this->input->get('groupid', true);
    	$lang = $this->lang->line('user_lang');
    	$out = "<option value=\"0\">".$lang['select']."</option>\n";
    	if($groupid <= 0)
    	{
    		echo $out; return;
    	}
    	
    	$sale = $this->user_model->get_sale_in_group($groupid);
    	if(count($sale) > 0) foreach ($sale as $row)
    	{
    		$out .= "<option value=\"".$row->user_id."\">".$row->username."</option>\n";
    	}
    	
    	echo $out;
    }
    function disable_agency()
    {
        $groupid = $this->input->get('groupid');
        if(!is_numeric($groupid)||($groupid<0))
        {
            echo 'error';
            die;
        }
        $userid = $this->session->userdata('uid');
        if(!is_numeric($userid)||($userid<0))
        {
            echo 'error';
            die;
        }
        $count = $this->user_model->selfserving_admin_agency_disable($groupid,$userid);
        if($count==false)
        {
            echo 'error';
        } 
    }
}